<template>
  <el-drawer
    v-bind="$attrs"
    class="sv-el-drawer"
    ref="drawerRef"
    @open="openDrawer"
    @close="closeDrawer"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <template #header>
      <h3>{{ formMode == 'add' ? '新增' : '编辑' }}</h3>
    </template>
    <template #default>
      <el-form
        class="sv-el-form"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item prop="exam_index" label="试题序号" required>
          <el-input-number
            class="sv-el-input-number"
            v-model="formData.exam_index"
            placeholder="请输入试题序号"
            style="width: 50%"
            step-strictly
            :min="1"
          />
        </el-form-item>
        <el-form-item prop="exam_id" label="试题ID" required>
          <el-input
            class="sv-el-input"
            v-model="compExamId"
            placeholder="请输入试题ID"
            clearable
            disabled
          />
          <view class="text-green">注意：试题ID由『所属题库-单元章节-试题序号』自动生成且唯一</view>
        </el-form-item>
        <el-form-item prop="exam_name" label="试题题干" required>
          <view style="height: 440px; width: 100%">
            <sv-wangeditor
              v-if="showEditor"
              v-model:html="formData.exam_name"
              ref="editorRef"
              mode="simple"
              @change="changeEditor"
            ></sv-wangeditor>
          </view>
        </el-form-item>
        <el-form-item prop="exam_title" label="试题标题">
          <el-input v-model="formData.exam_title" placeholder="请输入试题标题" clearable />
        </el-form-item>
        <el-form-item prop="from_lib" label="所属题库" required>
          <sv-dict-select
            v-model="formData.from_lib"
            placeholder="请选择所属题库"
            :dictList="libDictList"
            keyName="lib_name"
            valueName="lib_id"
          ></sv-dict-select>
        </el-form-item>
        <el-form-item prop="unit" label="单元章节" required>
          <sv-dict-select
            v-model="formData.unit"
            placeholder="请选择单元章节"
            :dictList="unitDictList"
            keyName="value"
            valueName="key"
          ></sv-dict-select>
        </el-form-item>
        <el-form-item prop="exam_type" label="试题类型" required>
          <sv-dict-select
            v-model="formData.exam_type"
            placeholder="请选择试题类型"
            :dictList="examConfig.paperTypeDictList"
            keyName="label"
            valueName="key"
          ></sv-dict-select>
        </el-form-item>
        <el-form-item prop="exam_option" label="试题选项">
          <view style="height: 440px; width: 100%">
            <sv-wangeditor
              v-if="showEditor"
              v-model:html="tempExamOption"
              ref="optionEditorRef"
              mode="simple"
            ></sv-wangeditor>
          </view>
          <view class="text-green">
            注意：试题选项必须放入表格内，选项必须为单个字母且与答案对应
          </view>
        </el-form-item>
        <el-form-item prop="exam_answer" label="试题答案" required>
          <sv-dict-select
            v-model="formData.exam_answer"
            multiple
            filterable
            allow-create
            placeholder="请选择试题答案"
            :dictList="examAnswerDictList"
            keyName="key"
            valueName="value"
          ></sv-dict-select>
        </el-form-item>
        <el-form-item prop="analysis" label="答案解析">
          <view style="height: 440px; width: 100%">
            <sv-wangeditor
              v-if="showEditor"
              v-model:html="formData.analysis"
              ref="analysisEditorRef"
              mode="simple"
            ></sv-wangeditor>
          </view>
        </el-form-item>
        <el-form-item prop="comment" label="备注">
          <el-input
            v-model="formData.comment"
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watchEffect } from 'vue'
import { isEmpty } from 'lodash-es'
import examConfig from '@/uni_modules/sv-exam-plus/config.js'
import {
  parseRichTextToOptions,
  parseOptionsToRichText,
  presetTemplate
} from '@/uni_modules/sv-exam-plus/utils/index.js'
import { libList } from '@/service/api/lib'

const props = defineProps({
  formInit: {
    type: Object,
    default: {}
  },
  formMode: {
    type: String,
    default: 'add'
  }
})

const emits = defineEmits(['submit'])

// 表单数据
const formData = ref({})
// 初始数据
const formBase = {
  from_lib: '', // 所属的题库
  unit: '', // 单元章节
  exam_id: '', // 试题id, 格式由(from_lib)_(exam_index)组成
  exam_name: '', // 试题题干
  exam_title: '', // 试题标题
  exam_index: 1, // 试题序号
  exam_type: 0, // 试题类型：0 单选 1 多选 2 判断
  exam_option: [], // 需要从富文本中处理成 [{ key: 'A', value: 'A选项内容' }, ...]
  exam_answer: [], // 试题答案
  analysis: '', // 答案解析
  comment: '' // 备注
}

const examAnswerDictList = [
  { key: 'A', value: 'A' },
  { key: 'B', value: 'B' },
  { key: 'C', value: 'C' },
  { key: 'D', value: 'D' },
  { key: 'E', value: 'E' },
  { key: 'F', value: 'F' },
  { key: 'G', value: 'G' }
]

const libDictList = ref([])
const unitDictList = computed(() => {
  const findLib = libDictList.value?.find((item) => item.lib_id == formData.value.from_lib)
  return findLib?.lib_chapter || []
})

async function handleDictList() {
  const liblistRes = await libList()
  libDictList.value = liblistRes.data || []
}
handleDictList()

const compExamId = computed({
  set(newVal) {
    formData.value.exam_id = newVal
  },
  get() {
    formData.value.exam_id = `${formData.value.from_lib}-${formData.value.unit}-${formData.value.exam_index}`
    return formData.value.exam_id
  }
})

const tempExamOption = ref(presetTemplate)

watchEffect(() => {
  // 表单数据初始化更新
  formData.value = Object.assign({ ...formBase }, props.formInit)
})

// 校验规则
const rules = ref({
  exam_index: [{ required: true, message: '请输入试题序号', trigger: 'blur' }],
  exam_id: [{ required: true, message: '请输入试题ID', trigger: 'blur' }],
  exam_name: [{ required: true, message: '请输入试题题干', trigger: 'blur' }],
  from_lib: [{ required: true, message: '请输入所属题库', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单元章节', trigger: 'blur' }],
  exam_type: [{ required: true, message: '请选择试题类型', trigger: 'blur' }],
  // exam_option: [{ required: true, message: '请输入试题选项', trigger: 'blur' }],
  exam_answer: [{ required: true, message: '请输入试题答案', trigger: 'blur' }]
})

const drawerRef = ref() // 抽屉
const formRef = ref() // 表单
const showEditor = ref(false) // 富文本组件显隐

/**
 * 富文本
 */
const editorRef = ref()
const analysisEditorRef = ref()
const optionEditorRef = ref()

function changeEditor(e) {
  // console.log('==== changeEditor e :', e)
}

function openDrawer() {
  compExamId.value = `${formData.value.from_lib}-${formData.value.unit}-${formData.value.exam_index}`
  showEditor.value = true

  // 富文本初始化解析
  if (!isEmpty(formData.value.exam_option)) {
    tempExamOption.value = parseOptionsToRichText(formData.value.exam_option)
  }
}

function closeDrawer() {
  showEditor.value = false
  // 需要把模板还原
  tempExamOption.value = presetTemplate
}

// 关闭抽屉
function cancel() {
  drawerRef.value.handleClose()
}
// 确认提交表单
function confirm() {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      editorRef.value.save()
      optionEditorRef.value.save()
      analysisEditorRef.value.save()

      formData.value.exam_option = parseRichTextToOptions(tempExamOption.value)

      emits('submit', { data: formData.value, mode: props.formMode })
      drawerRef.value.handleClose()
    } else {
      console.log('==== 校验失败 :', fields)
    }
  })
}
</script>

<style lang="scss"></style>
